package org.entities;

import org.BlockMap;
import org.Progress;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Animation;
import org.newdawn.slick.Sound;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.SlickException;

public class Ship extends LevelObject {

    //private float dx=0;
    private float dy=0;
    public Animation fallback,beam;
    public static final float MOVE_SPEED=0.05f;   
    private static int size[]={-80,0,112,0,112,90,-80,90};    
    private boolean shipGo;
    private Sound teleport;
    private boolean soundControl;

    public Ship(int x,int y,String type) throws SlickException {

        super(x, y,
                x+size[0],y+size[1], 
                x+size[2],y+size[3],
                x+size[4],y+size[5],
                x+size[6],y+size[7],
                type);

        SpriteSheet sheet=new SpriteSheet("data/image/ship.png",192,96);
        fallback=new Animation();
        //for (int frame=0;frame<3;frame++) {
        fallback.addFrame(sheet.getSprite(0,0), 250);
        //}
        SpriteSheet sheet2=new SpriteSheet("data/anim/beam.png",32,80);
        beam=new Animation();
        for (int frame=0;frame<5;frame++) {
            beam.addFrame(sheet2.getSprite(frame,0), 250);
        }
        beam.setAutoUpdate(false);
        fallback.setAutoUpdate(false);
        teleport = new Sound("data/sound/teleport.ogg");
    }


    public void update(int delta) throws SlickException {

        shipTime(delta);

        // prevent ship to cross map borders 
        if (x < 0){ x = 0;destroy();}
        if (y < 0){ y = 0;destroy();}     
        if (x > BlockMap.mapWidth -48){ x=BlockMap.mapWidth -48;destroy();}
        if (y > BlockMap.mapHeight-48){ y=BlockMap.mapHeight-48;destroy();}
    }


    public void shipTime(long delta){

        dy = (float)delta*MOVE_SPEED ;    
        y=poly.getY();
        x=poly.getX();
        if (!soundControl){
            soundControl=true;
            teleport.play(1,Progress.sfxVol/20);
        }
        if (!teleport.playing()) {
            shipGo=true;
        }
        if (!shipGo) {            
            beam.update(delta);
            Player.Freeze=true;
            
        }

        if (shipGo){
            y-=dy;
            poly.setY(y);
            Player.Freeze=false;
            Progress.ingame=true; // the ship go, we start playing. (start map music)
        }  
    }   



    //Destroy bullet going to left or right
    public void destroy() { 
        BlockMap.entities.remove(this); 
    }

    public void draw(Graphics g) {
        if (debugMode)
            g.draw(poly);   
        g.drawAnimation(fallback, poly.getX(), poly.getY());
        if (!shipGo)
            g.drawAnimation(beam, poly.getCenterX()-16, poly.getY()+80);
    }
}